﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using HKEA.CMS.Core.Models;
using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.App;
using System.Web.SessionState;

namespace WebApplication.ServerAshxFile
{
    /// <summary>
    /// M_JqueryUploadHandler 的摘要说明
    /// </summary>
    public class M_JqueryUploadHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            Routing(context);
        }
        /// <summary>
        /// 处理分支 路由
        /// </summary>
        /// <param name="context"></param>
        private void Routing(HttpContext context)
        {
            string mediaType = context.Request.QueryString["mediaType"];
            if (mediaType == Constant.MediaType.image)
                AddOrUpdateImage(context);
            else if (mediaType == Constant.MediaType.video)
                AddOrUpdateVideo(context);
            else
                AddOrUpdateImage(context);
        }

        /// <summary>
        /// 图片类 分支
        /// </summary>
        /// <param name="context"></param>
        private void AddOrUpdateImage(HttpContext context)
        {
            string add_update = context.Request.QueryString["add_update"];
            if (add_update == "add")
                AddMediaRoomPhoto(context);
            else if (add_update == "update")
                UpdateMediaRoomPhoto(context);
            else
                AddMediaRoomPhoto(context);
        }

        /// <summary>
        /// 视频类分支
        /// </summary>
        /// <param name="context"></param>
        private void AddOrUpdateVideo(HttpContext context)
        {
            string add_update = context.Request.QueryString["add_update"];
            if (add_update == "add")
                AddMediaRoomVideo(context);
            else if (add_update == "update")
                UpdateMediaRoomVideo(context);
            else
                AddMediaRoomVideo(context);
        }

        /// <summary>
        /// 上传一张mediaroom图片和 保存一条app_mediaroom记录
        /// </summary>
        /// <param name="context"></param>
        private void AddMediaRoomPhoto(HttpContext context)
        {
            string type = context.Request.QueryString["type"];
            string custUID = context.Request.QueryString["custuid"];
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            HttpPostedFile file = context.Request.Files["Filedata"];
            string uploadPath = HttpContext.Current.Server.MapPath(@GetFilePath(type));//HttpContext.Current.Server.MapPath(@context.Request["folder"]);

            if (file != null && !string.IsNullOrEmpty(custUID) && !string.IsNullOrEmpty(type))
            {
                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);

                tblCustomer entCustomer = new tblCustomer();
                entCustomer = tblCustomerBLL.GetInstance().GetEntity(int.Parse(custUID));

                string file_prefix = Common.CommonUploadImagesSquare(file, uploadPath, entCustomer.CustomerID);//先传了通用尺寸的图片后返回 文件名前缀
                iMaker.Library.FileOperate.ResizeImage(file, string.Format("{0}\\{1}_{2}.{3}", uploadPath, file_prefix, "200_120", "jpg"), 200, 120);
                iMaker.Library.FileOperate.ResizeImage(file, string.Format("{0}\\{1}_{2}.{3}", uploadPath, file_prefix, "600_400", "jpg"), 600, 400);

                //保存media room实体
                app_tblMediaRoom entMediaRom = new app_tblMediaRoom();
                //tblMediaRoom entMediaRom = new tblMediaRoom();
                entMediaRom.Category = GetCategory(type);
                //entMediaRom.MediaRoomUID = 0;
                entMediaRom.CustomerUID = string.IsNullOrEmpty(custUID) ? -1 : int.Parse(custUID);
                entMediaRom.AliasName = "";
                entMediaRom.FileName = file_prefix;
                entMediaRom.FilePath = GetFilePath(type);
                entMediaRom.FileExt = ".jpg";
                entMediaRom.IsPublish = 1;
                entMediaRom.MediaType = Constant.MediaType.image;
                entMediaRom.IsDeleted = Constant.IsDelete.no;
                entMediaRom.LastModifyBy = context.Session[Constant.SessionName.Manage] == null ? "system" : (context.Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                //int ret3 = tblMediaRoomBLL.GetInstance().InsertENT(entMediaRom);
                int ret = app_tblMediaRoomBLL.GetInstance().InsertENT(entMediaRom);
                context.Response.Write("1");
            }
            else
                context.Response.Write("0");
        }

        /// <summary>
        /// 修改Mediaroom的一张图片
        /// </summary>
        /// <param name="context"></param>
        private void UpdateMediaRoomPhoto(HttpContext context)
        {
            string tmp_mediaroomUID = context.Request.QueryString["mediaroomUID"];
            string custUID = context.Request.QueryString["custuid"];
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            HttpPostedFile file = context.Request.Files["Filedata"];
            int mediaroomUID = 0;
            int.TryParse(tmp_mediaroomUID, out mediaroomUID);
            app_tblMediaRoom entMediaRom = app_tblMediaRoomBLL.GetInstance().GetEntity(mediaroomUID);
            if (entMediaRom != null)
            {
                string uploadPath = HttpContext.Current.Server.MapPath(@entMediaRom.FilePath);
                string fileName = entMediaRom.FileName;

                tblCustomer entCustomer = new tblCustomer();
                entCustomer = tblCustomerBLL.GetInstance().GetEntity(int.Parse(custUID));

                if (file != null && !string.IsNullOrEmpty(custUID))
                {
                    if (!Directory.Exists(uploadPath))
                        Directory.CreateDirectory(uploadPath);

                    string file_prefix = Common.CommonUploadImagesSquare(file, uploadPath, entCustomer.CustomerID);//先传了通用尺寸的图片后返回 文件名前缀

                    //iMaker.Library.PTImage.ZoomAuto(file, string.Format("{0}\\{1}_{2}.{3}", uploadPath, file_prefix, "200_120", "jpg"), 200, 120, "", "");//传需要尺寸的图片
                    //iMaker.Library.PTImage.ZoomAuto(file, string.Format("{0}\\{1}_{2}.{3}", uploadPath, file_prefix, "600_400", "jpg"), 600, 400,"","");//传需要尺寸的图片
                    iMaker.Library.FileOperate.ResizeImage(file, string.Format("{0}\\{1}_{2}.{3}", uploadPath, file_prefix, "200_120", "jpg"), 200, 120);//传需要尺寸的图片
                    iMaker.Library.FileOperate.ResizeImage(file, string.Format("{0}\\{1}_{2}.{3}", uploadPath, file_prefix, "600_400", "jpg"), 600, 400);//传需要尺寸的图片


                    //删除图片
                    string oldFilePath = string.Format("~{0}{1}", entMediaRom.FilePath, entMediaRom.FileName);
                    if (!string.IsNullOrEmpty(context.Server.MapPath(oldFilePath)))
                    {
                        File.Delete(context.Server.MapPath(oldFilePath + "_37_37.jpg"));
                        File.Delete(context.Server.MapPath(oldFilePath + "_50_50.jpg"));
                        File.Delete(context.Server.MapPath(oldFilePath + "_100_100.jpg"));
                        File.Delete(context.Server.MapPath(oldFilePath + "_150_150.jpg"));
                        File.Delete(context.Server.MapPath(oldFilePath + "_200_200.jpg"));
                        File.Delete(context.Server.MapPath(oldFilePath + "_200_120.jpg"));
                        File.Delete(context.Server.MapPath(oldFilePath + "_600_400.jpg"));
                    }
                    //修改实体里的图片路径和名字               
                    entMediaRom.FileName = file_prefix;
                    int ret = app_tblMediaRoomBLL.GetInstance().UpdateENT(entMediaRom);

                    context.Response.Write("1");
                }
                else
                    context.Response.Write("0");
            }
            else
                context.Response.Write("0");
        }

        /// <summary>
        /// 添加一个视频
        /// </summary>
        /// <param name="context"></param>
        private void AddMediaRoomVideo(HttpContext context)
        {
            string ret = "0";
            string type = context.Request.QueryString["type"];
            string custUID = context.Request.QueryString["custuid"];
            string aliasName = context.Request.QueryString["aliasName"];

            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            HttpPostedFile file = context.Request.Files["Filedata"];
            string uploadPath = HttpContext.Current.Server.MapPath(@GetFilePath(type));

            if (file != null && !string.IsNullOrEmpty(custUID) && !string.IsNullOrEmpty(type))
            {
                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);

                tblCustomer entCustomer = new tblCustomer();
                entCustomer = tblCustomerBLL.GetInstance().GetEntity(int.Parse(custUID));

                string filename = file.FileName;//文件名字
                int filesize = file.ContentLength;//文件大小
                string filetype = file.ContentType;//文件类型
                string fileExt = System.IO.Path.GetExtension(filename).ToLower();

                string file_prefix = entCustomer.CustomerID + "_" + DateTime.Now.ToString("yyyyMMddhhmmss");
                bool isuploaded = iMaker.Library.FileOperate.UploadFile(file, string.Format("{0}\\{1}{2}",
                    uploadPath, file_prefix,
                    fileExt
                    )
                    );

                if (isuploaded)
                {
                    //保存media room实体
                    //tblMediaRoom entMediaRom = new tblMediaRoom();
                    app_tblMediaRoom entMediaRom = new app_tblMediaRoom();
                    entMediaRom.Category = GetCategory(type);
                    entMediaRom.CustomerUID = string.IsNullOrEmpty(custUID) ? -1 : int.Parse(custUID);
                    entMediaRom.AliasName = string.IsNullOrEmpty(aliasName) ? string.Empty : aliasName;
                    entMediaRom.FileName = file_prefix;
                    entMediaRom.FilePath = GetFilePath(type);
                    entMediaRom.FileExt = fileExt;
                    entMediaRom.IsPublish = 1;
                    entMediaRom.MediaType = Constant.MediaType.video;
                    //int retValue = tblMediaRoomBLL.GetInstance().InsertENT(entMediaRom);
                    int retValue = app_tblMediaRoomBLL.GetInstance().InsertENT(entMediaRom);
                    if (retValue > 0)
                        ret = "1";
                }
            }
            context.Response.Write(ret);
        }

        private void UpdateMediaRoomVideo(HttpContext context)
        {

        }

        private string GetCategory(string strType)
        {
            string strRet = string.Empty;
            if (!string.IsNullOrEmpty(strType))
            {
                switch (strType.ToLower())
                {
                    case "customerlogo":
                        strRet = Constant.MediaRoomCategory.customer_logo;
                        break;
                    case "contactpersonphoto":
                        strRet = Constant.MediaRoomCategory.contactperson_photo;
                        break;
                    case "branchimg":
                        strRet = Constant.MediaRoomCategory.branch_image;
                        break;
                    case "brandlogo":
                        strRet = Constant.MediaRoomCategory.brand_logo;
                        break;
                    case "productimg":
                        strRet = Constant.MediaRoomCategory.product_image;
                        break;
                    case "branchvideo":
                        strRet = Constant.MediaRoomCategory.branch_video;
                        break;
                    default:
                        break;
                }
            }
            return strRet;
        }


        private string GetFilePath(string strType)
        {
            string strRet = string.Empty;
            if (!string.IsNullOrEmpty(strType))
            {
                switch (strType.ToLower())
                {
                    case "customerlogo":
                        strRet = Constant.PathInfo.CustomerLogo;
                        break;
                    case "contactpersonphoto":
                        strRet = Constant.PathInfo.ContactPersonPhoto;
                        break;
                    case "branchimg":
                        strRet = Constant.PathInfo.BranchImg;
                        break;
                    case "brandlogo":
                        strRet = Constant.PathInfo.BrandLogo;
                        break;
                    case "productimg":
                        strRet = Constant.PathInfo.ProductImg;
                        break;
                    case "branchvideo":
                        strRet = Constant.PathInfo.BranchVideo;
                        break;
                    default:
                        break;
                }
            }
            return strRet;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}